use std::process::{exit, Command};

fn main() {
    // Run the 'chcp 437' command to set the command prompt window output to English
    let chcp_output = Command::new("cmd")
        .args(&["/C", "chcp", "437"])
        .output()
        .expect("Failed to execute chcp");

    if !chcp_output.status.success() {
        println!("Failed to set command prompt output to English");
        exit(1);
    }

    // Run the 'netsh wlan show interfaces' command and capture the output 中文操作系统
    let output = Command::new("netsh")
        .args(&["wlan", "show", "interfaces"])
        .output()
        .expect("Failed to execute netsh");

    // Convert the output to a string
    let output_str = String::from_utf8_lossy(&output.stdout);
    println!("{}", output_str);

    // 上面已经设置了英文，这里的中文就没用了，而且这里只支持 UTF8，对于 GBK 的中文操作系统，这里会乱码，导致找不到名称
    let names = vec!["Name", "名称"];
    // Find the ("Name" 或 "名称") in the output
    let name = output_str
        .lines()
        .find(|line| names.iter().any(|&name| line.contains(name)))
        .and_then(|line| line.split_whitespace().last())
        .expect("Failed to find name");

    println!("{}", name);

    // Run the netsh interface ip show addresses "%interface%" command and capture the output
    let output = Command::new("netsh")
        .args(&["interface", "ip", "show", "addresses", name])
        .output()
        .expect("Failed to execute netsh");

    // Convert the output to a string
    let output_str = String::from_utf8_lossy(&output.stdout);

    // Find the IP address in the output
    let names: Vec<&str> = vec!["Default Gateway", "默认网关"];
    let gateway_address = output_str
        .lines()
        .find(|line| names.iter().any(|&name| line.contains(name)))
        .and_then(|line| line.split_whitespace().last())
        .expect("Failed to find gateway address");

    println!("Gateway address: {}", gateway_address);

    // netsh interface ipv4 set dns name="Wi-Fi" static %gateway% primary
    // Set wifi with name='name' the DNS to the gateway address
    let set_dns_output = Command::new("netsh")
        .args(&["interface", "ipv4", "set", "dns", &format!("name=\"{}\"", name), "static", gateway_address])
        .output()
        .expect("Failed to execute netsh");

    // Check if setting the DNS was successful
    if set_dns_output.status.success() {
        println!("DNS set to {}", gateway_address);
    } else {
        println!("Failed to set DNS");
    }
}
